package NewTmas.FramesandPanels;

import NewTmas.Listeners.*;
import taskmaster.auth.User;
import taskmaster.job.TaskBuilder;
import taskmaster.util.LookupLists;

import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.*;


public class OpsModeMainFrame extends JFrame
{


    User user;
    JMenu window;
    JMenuBar menuBar;
    JDesktopPane dtp;
    TaskBuilder tb;
    LookupLists ll;
    public static Hashtable<Integer, String> status_name;
    public static Hashtable<Integer, String> status_category;
    public static Hashtable<String, String> roleHash = new Hashtable<String, String>();
    Date dateToSave;
    String[] libToSave;
    HashMap<String, String> signoffMap = new HashMap<String, String>();


    OpsModeMainFrame(final User user, LookupLists ll, TaskBuilder tb)
    {

        this.user = user;
        this.ll = ll;
        this.tb = tb;


        status_name = this.ll.getAllStatusesHash();
        String[][] statusInfo = new String[0][];

        try
        {
            statusInfo = this.ll.getAllStatuses();
            signoffMap = getSignoffSourceMap();
        } catch (Exception e)
        {

            JOptionPane.showMessageDialog(null, e.getMessage(), "Error getting the LookupList status", JOptionPane.ERROR_MESSAGE);
            e.printStackTrace();
        }
        roleHash = this.ll.getAllRolesHash();
        status_category = new Hashtable<Integer, String>();
        for (int i = 0; i < statusInfo.length; i++)
        {

            status_category.put(Integer.valueOf(statusInfo[i][0]), statusInfo[i][2]);
        }
        libToSave = new String[]{"GraphViz", "JGraphX"};

        setTitle("Ops Mode for " + user.getUserNameDatabaseString());


        setSize(1100, 950);

        setLocation(20, 20);

        dtp = new JDesktopPane();


        setContentPane(dtp);
        menuBar = new JMenuBar();
        setJMenuBar(menuBar);
        JMenu file = new JMenu("File");
        window = new JMenu("Window");
        JMenuItem jobOpener = new JMenuItem("Open Job Collection");
        file.add(jobOpener);
        JMenuItem jobstates = new JMenuItem("View Job Daemon states");
        file.add(jobstates);
        JMenu arrangeWindows = new JMenu("Arrange Windows");
        JCheckBoxMenuItem tile = new JCheckBoxMenuItem("Tile");
        JCheckBoxMenuItem cascade = new JCheckBoxMenuItem("Cascade");
        arrangeWindows.add(tile);
        arrangeWindows.add(cascade);
        JMenu windowMenu = new JMenu("Window");
        windowMenu.add(window);
        windowMenu.add(arrangeWindows);
        JMenuItem logout = new JMenuItem("Logout");
        file.add(logout);
        menuBar.add(file);
        menuBar.add(windowMenu);
        tile.addItemListener(new TileWindowStateListener(dtp, tile));
        cascade.addItemListener(new CascadeWindowStateListener(dtp, cascade));


        JMenuItem menuitem_exit;

        file.add(menuitem_exit = new JMenuItem("Exit"));

        window.addMenuListener(new WindowOpenListener(this.window, dtp));

        dateToSave = Calendar.getInstance().getTime();

        jobOpener.addActionListener(new JobOpenButtonListener(this));

        jobstates.addActionListener(new DaemonStatesOpenListener(this.tb, user, dtp, signoffMap, ll.getAllRolesHash()));

        logout.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {

                user.logout();
                LoginFrame l = new LoginFrame("", "", "");
                dispose();
            }
        });

        menuitem_exit.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent e)
            {
                try
                {
                    user.getConnection().close();
                } catch (SQLException e1)
                {
                    JOptionPane.showMessageDialog(null, e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                }
                System.exit(0);
            }
        });


        setVisible(true);
        addWindowListener(new WindowAdapter()
        {
            public void windowClosing(WindowEvent e)
            {
                try
                {
                    user.getConnection().close();
                } catch (SQLException e1)
                {
                    JOptionPane.showMessageDialog(null, e1.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
                    //e1.printStackTrace();
                    System.err.println("error closing the connection:");
                }
                setVisible(false);
                dispose();
                System.exit(0);
            }
        });
    }

    public User getUser()
    {
        return user;
    }

    public JDesktopPane getDtp()
    {
        return dtp;
    }

    public TaskBuilder getTb()
    {
        return tb;
    }

    public LookupLists getLl()
    {
        return ll;
    }

    public HashMap<String, String> getSignoffSourceMap() throws SQLException
    {

        HashMap<String, String> map = new HashMap<String, String>();
        Connection con = user.getConnection();
        Statement st = con.createStatement();
        String sql = "Select job_tag,command from tms.tasks where command like '%taskstatus%' ";
        ResultSet rs1 = st.executeQuery(sql);
        while (rs1.next())
        {
            final String commandString = rs1.getString("command");
            final String jobTag = rs1.getString("job_tag");
            // skip conditional commands that are checking for status (instead of setting it)
            if (commandString.startsWith("if"))
            {
                continue;
            }
            StringTokenizer stringTokenizer = new StringTokenizer(commandString);
            while (stringTokenizer.hasMoreElements())
            {
                String commandToken = stringTokenizer.nextToken();
                if (commandToken.contains(":"))
                {
                    //System.out.print("\n"+commandToken);
                    String key = commandToken.replaceAll("[^A-Z : _ 0-9]", "");
                    map.put(key, jobTag);
                }
            }
        }
        rs1.close();
        st.close();
        return map;
    }


}







